import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { Field, reduxForm } from 'redux-form';
import {
  Select,
  TextField,
  Row,
  Col,
  Button,
  TextArea
} from '@folio/stripes/components';

import css from './style.css';

function validate(values, props) {
  const errors = {};

  if (!values || !values.name) {
    errors.name = (
      <FormattedMessage id="ui-users.errors.missingRequiredField" />
    );
  }
  if (!values || !values.template) {
    errors.template = (
      <FormattedMessage id="ui-users.errors.missingRequiredField" />
    );
  }
  if (!values || !values.type) {
    errors.type = (
      <FormattedMessage id="ui-party.messageTemplate.errors.type" />
    );
  }

  if (!values || !values.notice) {
    errors.notice = (
      <FormattedMessage id="ui-party.messageTemplate.errors.notice" />
    );
  }
  return errors;
}

function asyncValidateField(field, value, validator) {
  return new Promise((resolve, reject) => {
    const query = {
      jsonb: {}
    };
    query.jsonb[field] = value;
    validator.reset();
    const queryParams = `isDel = 0 and name = ${value}`;
    return validator.GET({ params: { query: queryParams } }).then(result => {
      if (result.totalRecords > 0) {
        const error = { jsonb: {} };
        error.jsonb[field] = (
          <FormattedMessage id="ui-party.messageTemplate.data.name.error" />
        );
        return reject(error);
      } else {
        return resolve();
      }
    });
  });
}

function asyncValidate(values, dispatch, props, blurredField) {
  const {
    uniquenessValidator,
    initialValues,
    match: { params }
  } = props;
  const { name } = values;
  if (params.id) {
    return new Promise((resolve, reject) => {
      return resolve();
    });
  }

  if (name) {
    values.name = name.trim();
  }
  const curValue = values[blurredField];
  const prevValue = initialValues[blurredField];

  // validate on blur
  if (blurredField && curValue && curValue !== prevValue) {
    return asyncValidateField(blurredField, curValue, uniquenessValidator);
  }

  const promises = [];

  // validate on submit

  if (name !== initialValues.name) {
    promises.push(asyncValidateField('name', name, uniquenessValidator));
  }
  return Promise.all(promises);
}

class Form extends React.Component {
  static propTypes = {
    history: PropTypes.object,
    handleSubmit: PropTypes.func.isRequired,
    initialValues: PropTypes.object,
    dictionary: PropTypes.object,
    uniquenessValidator: PropTypes.shape({
      reset: PropTypes.func.isRequired,
      GET: PropTypes.func.isRequired
    }).isRequired,
    toModel:PropTypes.func,
    cancel:PropTypes.func,
  };

  handleCancel = () => {
    this.props.history.push('/activity/messageTemplate/list');
  };

  render() {
    const { toModel, handleSubmit, initialValues, dictionary,cancel } = this.props;
    const noticeOptions = ((dictionary || {}).notice || []).map(g => {
      const selected = (initialValues  || {}).notice === g.id;
      return (
        <FormattedMessage key={g.id} id={g.desc}>
          {message => (
            <option selected={selected} value={g.id}>
              {message}
            </option>
          )}
        </FormattedMessage>
      );
    });

    const typeOptions = ((dictionary || {}).type || []).map(g => {
      const selected = (initialValues || {}).type === g.id;
      return (
        <FormattedMessage key={g.id} id={g.desc}>
          {message => (
            <option selected={selected} value={g.id}>
              {message}
            </option>
          )}
        </FormattedMessage>
      );
    });

    const stateOptions = ((dictionary || {}).state || []).map(g => {
      const selected = (initialValues  || {}).state === g.id;
      return (
        <FormattedMessage key={g.id} id={g.desc}>
          {message => (
            <option selected={selected} value={g.id}>
              {message}
            </option>
          )}
        </FormattedMessage>
      );
    });

    return (
      <div>
        <form
          data-test-form-page
          id="form-message-template"
          onSubmit={handleSubmit}
          className={css.formClass}
        >
          <Row className={css.formClass}>
            <Col xs={12}>
              <div className={css.formContentClass}>
                <Row>
                  <Col xs={4}>
                    <Field
                      component={TextField}
                      label={
                        <FormattedMessage id="ui-party.messageTemplate.name" />
                      }
                      name="name"
                      required
                    />
                  </Col>

                  <Col xs={4}>
                    <Field
                      component={Select}
                      label={
                        <FormattedMessage id="ui-party.messageTemplate.notice" />
                      }
                      name="notice"
                      required
                    >
                      {noticeOptions}
                    </Field>
                  </Col>
                  <Col xs={4}>
                    <Field
                      component={Select}
                      label={
                        <FormattedMessage id="ui-party.messageTemplate.type" />
                      }
                      name="type"
                      required
                    >
                      {typeOptions}
                    </Field>
                  </Col>
                </Row>
                <Row>
                  <Col xs={12}>
                    <Field
                      component={TextArea}
                      label={
                        <FormattedMessage id="ui-party.messageTemplate.template" />
                      }
                      name="template"
                      fullWidth
                      required
                      className={css.areaClass}
                    />
                    <div
                      style={{
                        fontSize: '12px',
                        color: 'rgb(172, 170, 170)',
                        lineHeight: '22px'
                      }}
                    >
                      <FormattedMessage id="ui-party.messageTemplate.template.tip" />
                    </div>
                  </Col>
                </Row>
                <Row />
                <Row>
                  <Col xs={12}>
                    <Button
                      onClick={() => cancel(false)
                      }
                    >
                      <FormattedMessage id="ui-party.cancel" />
                    </Button>
                    <Button type="submit">
                      <FormattedMessage id="ui-party.saveAndExit" />
                    </Button>
                  </Col>
                </Row>
              </div>
            </Col>
          </Row>
        </form>
      </div>
    );
  }
}
export default reduxForm({
  form: 'MessageTemplateForm',
  validate,
  asyncValidate,
  asyncBlurFields: ['name'],
  navigationCheck: true,
  enableReinitialize: true
})(Form);
